/**
 * Created by charsen on 16/5/25.
 */
directives.directive('newFolder', ["$rootScope", "tools", "$timeout", "userConfig", function ($rootScope, tools, $timeout, userConfig) {
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        link: function (scope, element, attr) {
            scope.pages = [];
            var origin_name = "";

            $rootScope.$on('NEW_FOLDER_EV', function (e) {
                scope.folderName = "";
                scope.pages = angular.copy($rootScope.getAllPages());
                $(element).modal('show');
            });

            $rootScope.$on('EDIT_FOLDER_EV', function (e, folder) {
                scope.folderName = origin_name = folder.name;
                scope.pages = angular.copy(folder.pages);

                angular.forEach(scope.pages, function (page) {
                    page.checked = true;
                });

                scope.pages = scope.pages.concat(angular.copy($rootScope.getAllPages()));

                $(element).modal('show');
            });

            scope.close = function () {
                $(element).modal('hide');
            }

            scope.errinfo = "";
            scope.folderName = "";

            scope.ensure = function () {
                if (!scope.folderName) {
                    scope.errinfo = "文件夹的名称不能为空哦~";
                    $timeout(function () {
                        scope.errinfo = "";
                    }, 2000);
                    return;
                }

                var config = userConfig.getUserConfig();
                if (!config.folders) {
                    config.folders = {};
                }

                if (!config.folders[scope.folderName]) {
                    config.folders[scope.folderName] = [];
                }

                angular.forEach(scope.pages, function (page, index) {
                    if (page.checked) {
                        if (config.folders[scope.folderName].indexOf(page.pageId) === -1) {
                            config.folders[scope.folderName].push(page.pageId);
                        }
                    } else {
                        if (config.folders[scope.folderName].indexOf(page.pageId) != -1) {
                            config.folders[scope.folderName].splice(config.folders[scope.folderName].indexOf(page.pageId), 1);
                        }
                    }
                });

                if (origin_name != scope.folderName) {
                    delete config.folders[origin_name];
                }

                scope.folderName = "";

                userConfig.updateUserConfig(function () {
                    $rootScope.$broadcast('UPDATE_FOLDER_INFO');
                    scope.close();
                });
            }
        },
        templateUrl: "/trend-new-BI/app/components/common/newFolder/newFolderView.html"
    }
}]);